package com.sihai.ehr.web.action.exam;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.EmployeeinfoWork;
import com.sihai.ehr.model.biz.ExamPeriod;
import com.sihai.ehr.model.biz.ExamQuanScoreDetail;
import com.sihai.ehr.model.sys.ExaminePeriodEnum;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.*;
import com.sihai.ehr.utils.PeriodUtils;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.ExamStatisticsPojo;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

@Results({
        @Result(name = "main",location = "exam_history_main.jsp"),
        @Result(name="list",location="exam_quan_history_score_list.jsp"),
        @Result(name="detail",location="/WEB-INF/pages/exam/exam_quan_history_score_detail.jsp"),
        @Result(name="score_details",location="exam_quan_score_detail.jsp"),
        @Result(name="quan_score_browse_user",location="/WEB-INF/pages/exam/exam_qual_score_browse_user.jsp")
})
public class ExamQuanHistoryAction extends EHRAction{

    @BeanInject
    private OrganizationService organizationService;
    @BeanInject
    private EmployeeService employeeService;
    @BeanInject
    private ExamPeriodService examPeriodService;
    @BeanInject
    private ExamQuanDataInputService examQuanDataInputService;
    @BeanInject
    private ExamStatisticsService examStatisticsService;
    @BeanInject
    private UserService userService;

    private List<Organization> organizations;

    private Long searchOrgId; //搜索部门id
    private Long dutyId;    //职务ID
    private ExaminePeriodEnum type;//周期类型
    private EmployeeinfoWork work;

    private List<ExamPeriod> examPeriods;
    private LimitedList<ExamStatisticsPojo> examStatisticsPojos;

    private List<ExamQuanScoreDetail> details;

    private List[] chartDatas;

    private String module = "qual_browse";

    @Action("/exam/quan_history_main")
    @Override
    public String execute() throws Exception{
        listAction="/exam/quan_histroy_list.xhtml";
        listTitle="定量考核-考核历史浏览";

        organizations = organizationService.findChildren(null, true, null, null);
        if (organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
        showChildOrg = true;
        return "main";
    }

    /**
     * 查询定量考核历史记录
     *
     * @return
     * @throws Exception
     */
    @Action("/exam/quan_histroy_list")
    public String scores() throws Exception {
        try {
            Calendar mCalendar = Calendar.getInstance();
            examPeriods = PeriodUtils.getLateThreeExamPeriodTOReverse(type, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH) + 1);
            if (examPeriods != null) {
                examStatisticsPojos = examStatisticsService.searchExamStatisticsPojos(2, organizationId, dutyId, type, examPeriods, createLimit(), createSorter());
                /* 分页 */
                this.paging(examStatisticsPojos);
                /* 设置翻页action */
                this.setPageUrl("exam/quan_histroy_list.xhtml");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "list";
    }

    @Action("/public/quan_score_browse_user")
    public String scoresForUser() throws Exception {
        Long userId = getCurrentUserId();
        if(userId == null || userId <= 0){
            return "quan_score_browse_user";
        }
        User user = userService.getUser(userId);
        if (user == null) {
            return "quan_score_browse_user";
        }

        topOrganizationName = user.getWork().getOrganization().getTopOrganization() == null ? user.getWork().getOrganization().getFullName() : user.getWork().getOrganization().getTopOrganization().getFullName();
        if(type == null){
            type = ExaminePeriodEnum.monthly;
        }
        try {
            Calendar mCalendar = Calendar.getInstance();
            examPeriods = PeriodUtils.getLateThreeExamPeriodTOReverse(type, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH) + 1);
            if (examPeriods != null) {
                examStatisticsPojos = examStatisticsService.searchExamStatisticsPojoForUser(2, user.getWork().getId(), type, examPeriods);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "quan_score_browse_user";
    }
    @Action("/public/quan_histroy_detail")
    public String queryUserHistoryQualDScoreByYear() throws Exception {
        Long userId = getCurrentUserId();
        if(userId == null || userId <= 0){
            return "quan_score_browse_user";
        }
        User user = userService.getUser(userId);
        if (user == null) {
            return ERROR;
        }
        work = user.getWork();
        if(work == null || work.getId() == null){
            return execute();
        }

        return "detail";
    }

    public int getHistory_list_type() {
        //return history_list_type;
        return 2;
    }
    private String topOrganizationName;
    public String getTopOrganizationName() {
        return topOrganizationName;
    }

    /**
     * 查询定量考核某一用户的全年历史记录
     * @return
     * @throws Exception
     */
    @Action("/exam/quan_histroy_detail")
    public String detail() throws Exception {
        if(work == null || work.getId() == null){
            return execute();
        }
        work = employeeService.getEmployeeinfoWork(work.getId());
        return "detail";
    }

    //得到指定年的全年定量考核数据
    @Action(value = "/ajax/quan_histroy_scores", results = { @Result(name = "success", type = "json", params = {"root", "chartDatas" }) })
    public String getScoresByYear() throws Exception {
        if(work == null || work.getId() == null || type == null){
            return ERROR;
        }
        work = employeeService.getEmployeeinfoWork(work.getId());
        int year = NumberUtils.createInteger(getParameter("year"));
        if(year == 0){
            year =Calendar.getInstance().get(Calendar.YEAR);
        }
        List<Object[]> list = examStatisticsService.findScoresByYear(work.getId(), type, year);
        if(list != null && list.size() > 0){
            int size = list.size();
            List<Float> scores = new ArrayList<Float>();
            List<String> periodNames = new ArrayList<String>(size);
            List<Long> periodIds = new ArrayList<Long>(size);
            for(Object[] objects : list){
                scores.add((Float)objects[0]);
                periodNames.add((String)objects[1]);
                periodIds.add((Long)objects[2]);
            }
            chartDatas = new List[3];
            chartDatas[0] = scores;
            chartDatas[1] = periodNames;
            chartDatas[2] = periodIds;
        }

        return SUCCESS;
    }

    //得到指定指定用户指定周期的定量考核数据
    @Action(value = "/exam/quan_histroy_details")
    public String getScoresDetails() throws Exception {
        if(work == null || work.getId() == null){
            return "score_details";
        }
        Long periodId = NumberUtils.createLong(getParameter("periodId"));
        if(periodId == null || periodId <= 0){
            return "score_details";
        }
        details = examQuanDataInputService.findExamQuanScoreDetails(work.getId(), periodId);


        return "score_details";
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public void setOrganizations(List<Organization> organizations) {
        this.organizations = organizations;
    }

    public Long getSearchOrgId() {
        return searchOrgId;
    }

    public void setSearchOrgId(Long searchOrgId) {
        this.searchOrgId = searchOrgId;
    }

    public Long getDutyId() {
        return dutyId;
    }

    public void setDutyId(Long dutyId) {
        this.dutyId = dutyId;
    }

    public ExaminePeriodEnum getType() {
        return type;
    }

    public void setType(ExaminePeriodEnum type) {
        this.type = type;
    }

    public EmployeeinfoWork getWork() {
        return work;
    }

    public void setWork(EmployeeinfoWork work) {
        this.work = work;
    }

    public String getModule() {
        return module;
    }

    public LimitedList<ExamStatisticsPojo> getExamStatisticsPojos() {
        return examStatisticsPojos;
    }

    public List<ExamPeriod> getExamPeriods() {
        return examPeriods;
    }

    public List[] getChartDatas() {
        return chartDatas;
    }

    public List<ExamQuanScoreDetail> getDetails() {
        return details;
    }
}